$(function () {
    imgLocation();
    var dataImg = {
        "data":[{"src":"001.jpg"},{"src":"002.jpg"},{"src":"003.jpg"},{"src":"006.jpg"},{"src":"009.jpg"},{"src":"010.jpg"}]
    };
    window.onscroll = function (){
        if(scrollSide()){
            $.each(dataImg.data,function (index,value){
                var box = $("<div>").addClass("box").appendTo($("#container"));
                var content = $("<div>").addClass("content").appendTo(box);
                content.append($("<img>").attr("src","./img/"+$(value).attr("src")));
            });
        }
        imgLocation();
    };
});

function scrollSide(){
    var aBox = $(".box");
    var iLastBoxTop = aBox.last().position().top+Math.round(aBox.last().innerHeight()/2);
    var documentHeight = $(window).height();
    var scrollTop = $(window).scrollTop();
    if(iLastBoxTop<documentHeight+scrollTop)
        return true;
};

function imgLocation() {
    var aBox = $(".box");
    var iBoxWidth = aBox.first().innerWidth();
    var iNum = Math.floor($(window).width()/iBoxWidth);
    $("#container").css({
        "width":iBoxWidth*iNum,
        "margin":"0 auto"
    });
    var aBoxHeight = [];
    $.each(aBox,function(index,value){
        var iBoxHeight = aBox.eq(index).innerHeight();
        if(index<iNum){
            aBoxHeight.push(iBoxHeight);
            // console.log(iBoxHeight);
        }else{
            var iMinBoxHeight = Math.min.apply(null,aBoxHeight);
            var iMinBoxIndex = $.inArray(iMinBoxHeight,aBoxHeight);
            $(value).css({
                "position":"absolute",
                "top":iMinBoxHeight,
                "left":aBox.eq(iMinBoxIndex).get(0).offsetLeft
            });
            aBoxHeight[iMinBoxIndex] += iBoxHeight;
        }
    })
};